package exercises.leetcode.utils;

/**
 * @author or2
 * @Description 将leetcode的数组输入的字符串转化为对应的java形式
 * @create 2021年09月20日 时间: 17:58
 */
public class ToArray {

    public static int[] toArray(String in) {
        in = in.substring(1, in.length() - 1);
        int[] ans = getInts(in);

        return ans;
    }

    private static int[] getInts(String in) {
        int[] ans;
        String[] ints = in.split(",");
        ans = new int[ints.length];
        for (int i = 0; i < ans.length; i++) {
            ans[i] = Integer.parseInt(ints[i]);
        }
        return ans;
    }

    public static int[][] toArrays(String in) {
        String[] ins = in.split("\n");
        int[][] ans = new int[ins.length][];
        for (int i = 0; i < ans.length; i++) {
            ans[i] = toArray(ins[i]);
        }

        return ans;
    }

    public static String replaceSquareBrackets(String str) {
        str = str.replaceAll("\\[", "{");
        str = str.replaceAll("]", "}");
        System.out.println(str);
        return str;
    }

    public static int[][] toInt2Array(String origin) {
        origin = origin.substring(2, origin.length() - 2);
        String[] layer1 = origin.split("],\\[");
        int[][] ans = new int[layer1.length][];
        for (int i = 0; i < layer1.length; i++) {
            ans[i] = getInts(layer1[i]);
        }

        return ans;
    }

    /**
     * 将 leetcode 中的字符串 -> char[][]
     *
     * @param str 输入字符串
     * @return 二维字符数组
     */
    public static char[][] string2Chars(String str) {
        str = str.substring(1, str.length() - 1);
        String[] layer = str.split("(?<=]),(?=\\[)");
        char[][] ans = new char[layer.length][];
        for (int i = 0; i < layer.length; i++) {
            ans[i] = toCharArray(layer[i]);
        }
        return ans;
    }

    /**
     * 将某一特定类型字符串 -> char一维数组
     *
     * @param str 字符串
     * @return 一维字符数组
     */
    private static char[] toCharArray(String str) {
        str = str.substring(1, str.length() - 1);
        String[] split = str.split(",");
        char[] ans = new char[split.length];
        for (int i = 0; i < ans.length; i++) {
            ans[i] = split[i].charAt(0);
        }
        return ans;
    }
}
